package com.algrithom.array;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * 1. 两数之和
 * 
 * @author think
 */
public class Solution2 {
    
    public static void main(String[] args){
        int[] nums = new int[]{};
        Solution2 solution2 = new Solution2();
        System.out.println(Arrays.toString(solution2.twoSum(nums,9)));
    }
    
    public int[] twoSum(int[] nums,int target){
        int len = nums.length;
        for (int i = 0; i < len; i++) {
            for (int j = i + 1; j < len; j++) {
                if (target - nums[i] == nums[j]) {
                    return new int[]{i,j};
                }
            }
        }
        return new int[]{};
    }
    
    public int[] twoSum2(int[] nums,int target){
        Map<Integer,Integer> hashtable = new HashMap<>();
        for (int i = 0; i < nums.length; ++i) {
            if (hashtable.containsKey(target - nums[i])) {
                return new int[]{hashtable.get(target - nums[i]),i};
            }
            hashtable.put(nums[i],i);
        }
        return new int[]{};
    }

    /**
     * 此方法只适用于数组有序的情况
     * @param numbers numbers
     * @param target target
     * @return array
     */
    public int[] twoSum3(int[] numbers, int target) {
        int len = numbers.length;
        int left = 0;
        int right = len - 1;
        while (left < right) {
            if (numbers[left] + numbers[right] < target) {
                left++;
            } else if (numbers[left] + numbers[right] > target) {
                right--;
            } else {
                return new int[]{left,right};
            }
        }
        return new int[]{};
    }
}
